<template>
  <el-upload
    class="avatar-uploader"
    action=""
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :http-request="onUpload"
  >
    <img v-if="value" :src="value" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDOmKiqnWDk27zc081iYDdqtiN2MXZTHsJ',
  SecretKey: 'KSVMm3B8uX0IQOCqKdooeKqCXijaHm6E'
})
export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },

  methods: {
    // 上传前的一个钩子函数，若返回 false 或者返回 Promise 且被 reject，则停止上传
    // 检查函数 判断文件的类型还有大小 return  true(继续上传)/false(停止上传)
    beforeAvatarUpload(file) {
      // 该图片格式可以上传
      const isJPG = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp'].includes(file.type)
      // 图片大小不能大于 2M
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }
      return isJPG && isLt2M
    },
    onUpload(e) {
      // 覆盖默认的上传行为，可以自定义上传的实现
      console.log(123, e)

      cos.putObject({
        Bucket: 'manpower-1318626660',
        Region: 'ap-nanjing',
        Key: e.file.name,
        StorageClass: 'STANDARD',
        Body: e.file
      }, (err, data) => {
        // 监听成功和失败回调函数
        console.log(data)
        if (data.statusCode === 200) {
          this.$emit('input', 'http://' + data.Location)
        } else {
          this.$message.success(err)
        }
      })
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
